package com.example.letswalk.service.serviceimpl;

import com.example.letswalk.dao.SysUserRoleMapper;
import com.example.letswalk.pojo.SysUser;
import com.example.letswalk.pojo.SysUserRole;
import com.example.letswalk.pojo.example.SysUserRoleExample;
import com.example.letswalk.service.SysUserRoleService;
import com.example.letswalk.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysUserRoleServiceImpl implements SysUserRoleService{

    @Autowired
    SysUserRoleMapper sysUserRoleMapper;


    /**
     * 通过SysUser,RoleId 设置联系 设置一个用户有什么角色
     * @param sysUser
     * @param roleIds
     */
    @Override
    public void setRoles(SysUser sysUser, Integer[] roleIds) {
        //删除当前用户所有的角色
        SysUserRoleExample example= new SysUserRoleExample();
        example.createCriteria().andUserIdEqualTo(sysUser.getUserId().intValue());
        List<SysUserRole> urs= sysUserRoleMapper.selectByExample(example);
        for (SysUserRole sysUserRole : urs)
            sysUserRoleMapper.deleteByPrimaryKey(sysUserRole.getId());

        //设置新的角色关系
        if(null!=roleIds)
            for (Integer rid : roleIds) {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setRoleId(rid);
                sysUserRole.setUserId(sysUser.getUserId().intValue());
                sysUserRoleMapper.insert(sysUserRole);
            }




    }

    /**
     * 通过UserId删除角色
     * @param userId
     */
    @Override
    public void deleteByUser(int userId) {
        SysUserRoleExample example = new SysUserRoleExample();
        example.createCriteria().andUserIdEqualTo(userId);
        List<SysUserRole> urs = sysUserRoleMapper.selectByExample(example);
        for (SysUserRole sysUserRole : urs) {
            sysUserRoleMapper.deleteByPrimaryKey(sysUserRole.getId());

        }
    }

    /**
     * 通过RoleId删除角色被赋予的用户
     * @param roleId
     */
    @Override
    public void deleteByRole(int roleId){
        SysUserRoleExample example= new SysUserRoleExample();
        example.createCriteria().andRoleIdEqualTo(roleId);
        List<SysUserRole> urs= sysUserRoleMapper.selectByExample(example);
        for (SysUserRole sysUserRole : urs) {
            sysUserRoleMapper.deleteByPrimaryKey(sysUserRole.getId());
        }
    }

}



